package com.gao.test;

import java.io.IOException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author gao
 * @time 2020/04/2020/4/23 21:40:24
 */
public class Demo09 {
    public static void main(String[] args) throws IOException {
        System.out.println("Enter...");
        System.in.read();
        System.out.println("开启了死循环线程");

        System.out.println("Enter...");
        System.in.read();
        System.out.println("开启了wait线程");
        waitThread(new Object());

        System.out.println("Enter...");
        System.in.read();
        System.out.println("开启了死锁线程");
        deadLock();

        System.out.println("Enter...");
        System.in.read();

        System.out.println("over");
    }

    public static void whileTrueThread() {
        new Thread(() -> {
            while (true);
        }, "whileTrueThread").start();
    }

    public static void waitThread(Object o) {
        new Thread(() -> {
            synchronized (o) {
                try {
                    o.wait();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "myWaited").start();
    }

    private static void deadLock() {
        Lock lock1 = new ReentrantLock();
        Lock lock2 = new ReentrantLock();

        new Thread(() -> {
            try {
                lock1.lock();
                Thread.sleep(100);
                lock2.lock();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock1.unlock();
                lock2.unlock();
            }
        }).start();

        new Thread(() -> {
            try {
                lock2.lock();
                Thread.sleep(100);
                lock1.lock();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock1.unlock();
                lock2.unlock();
            }
        }).start();

    }
}
